package com.zh.util

import java.io.FileInputStream._
import java.io.{BufferedReader, File, InputStreamReader}
import java.util.Properties


/**
 * Created by sparker
 */
object PropertiesUtils {

  final val prop = getPropConfig("/streaming.properties")

  //  /**
  //   * 读取配置文件
  //   *
  //   * @return
  //   */
  //  def getPropConfig(fileName: String): Properties = {
  //    val property = new Properties()
  //    val inputStream = getClass.getResourceAsStream(fileName)
  //    val InputStreamReader = new BufferedReader(new InputStreamReader(inputStream))
  //    property.load(InputStreamReader)
  //    property
  //  }

  /**
   * 读取配置文件
   *
   * @return
   */
  def getPropConfig(fileName: String): Properties = {
    val file = new File(fileName)
    val properties: Properties = new Properties
    if (!file.exists()) {
      val in = new BufferedReader(new InputStreamReader(getClass.getResourceAsStream(fileName)))
      properties.load(in)
    } else {
      import java.io.{BufferedInputStream, FileInputStream}
      val bis = new BufferedInputStream(new FileInputStream(fileName))
      properties.load(bis)
    }
    properties
  }

  /**
   * 发包是否是生产环境
   *
   * @return
   */
  def isPro(): Boolean = {
    val pattern = prop.getProperty("spark.product.flag").trim
    if ("true".equalsIgnoreCase(pattern)) true else false
  }


  /**
   * 通过key获取value
   *
   * @return
   */
  def getValue(paramNames: Array[String]): Array[String] = {
    val paramValues = paramNames.map { x =>
      prop.getProperty(x)
    }
    paramValues
  }

  def getValue(paramNames: String): String = {
    val paramValues = prop.getProperty(paramNames)
    paramValues
  }

  /**
   * 读取外部配置文件
   */
  def parseArgsFromFile(fileName: String, paramsArr: Array[String]): Array[String] = {
    val properties: Properties = new Properties
    import java.io.{BufferedInputStream, FileInputStream}
    val in = new BufferedInputStream(new FileInputStream(fileName))
    properties.load(in)
    val paramValues: Array[String] = paramsArr.map { x =>
      properties.getProperty(x)
    }
    paramValues
  }

}

